<!--
 - Author : chenyliu.
 - Date   : 2016/9/20.
 - File   : citypicker.vue.
 -->

<template>
  <div class="city-picker-dropdown" v-show="visible">
    <div class="city-select-wrap">
      <div class="city-select-tab clearfix">
        <span v-for="item in tabs"
                :class="{'active':tab === item.en}"
                @click="selected(item.en)">{{item.zh}}</span>
        <!--<button class="city-select-sure" @click="submitHandle">确 定</button>-->
        <button class="city-select-sure" @click="cancelHandle">取 消</button>
      </div>
      <div class="city-select-content">
        <div class="city-select" :class="'city-select-'+item.en"
                v-for="(index, item) in tabs"
                v-show="tab === item.en">
          <dl class="clearfix">
            <dd>
              <span :class="{'active': site[item.en].code == key}"
                      :title="val"
                      v-for="(key, val) in $data['temp' + item.en.charAt(0).toUpperCase() + item.en.slice(1)]"
                      @click="setData(item.en, key, val)"> {{val}}
              </span>
            </dd>
          </dl>
          <div class="empty" v-if="isEmpty(item.en)">
            <span v-if="!loading"><i>未选择上级</i> 或 <i>街道下没有社区</i></span>
            <span v-if="loading">数据加载中...</span>
          </div>
        </div>

        <div class="city-add" v-if="tab === 'community' ">
          <div>
            <a href="javascript:;" @click="submitHandle">不选择社区</a>
            <a href="javascript:;" @click="showAddCommunity">添加新社区</a>
          </div>
          <div v-show="adding">
            <input type="text" placeholder="新社区名称，添加后不可修改"
                    v-model="addCommunityName">
            <button @click="addCommunityHandle">添加</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import CityData from './city-data.js'
  import {apiSource} from '../../wohome-api'

  export default {
    data() {
      return {
        tab: 'province',
        tabs: [
          {
            en: 'province',
            zh: '省份',
          },
          {
            en: 'city',
            zh: '城市',
          },
          {
            en: 'district',
            zh: '区县',
          },
          {
            en: 'street',
            zh: '街道',
          },
          /*{
            en: 'community',
            zh: '社区'
          },*/

        ],
        last: 'street',
        site: {
          province: {
            code: '',
            text: '',
          },
          city: {
            code: '',
            text: '',
          },
          district: {
            code: '',
            text: '',
          },
          street: {
            code: '',
            text: '',
          },
          community: {
            code: '',
            text: '',
          }
        },
        loading: false,
        adding: false,
        tempProvince: {},
        tempCity: {},
        tempDistrict: {},
        tempStreet: {},
        tempCommunity: {},
        addCommunityName: ''
      }
    },
    ready() {
      this.tempProvince = CityData['86']
    },
    props: {
      selectCb: {
        type: Function,
        default: () => {
        }
      },
      submitCb: {
        type: Function,
        default: () => {
        }
      },
      cancelCb: {
        type: Function,
        default: () => {
        }
      },
      visible: {
        type: Boolean,
        default: false
      },
      debug: {
        type: Boolean,
        default: false
      }
    },
    methods: {
      /**
       * 选中 数据
       * @param {String} txt
       * @param {String} code
       * @param {String} text
       */
      setData(txt, code, text) {
        if(this.debug) {
          console.log(txt, code, text);
        }
        this.site[txt].code = code
        this.site[txt].text = text

        if(txt === this.last) {
          this.submitHandle()
          return
        }
        this.resetData(txt, code)
        this.selectCb(this.site)
      },
      /**
       * 重置 data
       * @param {String} txt
       * @param {String} code
       */
      resetData(txt, code) {
        let arr = this.tabs
        let reset = false
        let next = 0
        for(let i = 0; i < arr.length; i++) {
          if(txt == arr[i].en) {
            reset = true
            next = i + 1
            continue
          }
          if(reset) {
            this.site[arr[i].en].code = ''
            this.site[arr[i].en].text = ''
            this.resetTempData(arr[i].en)
          }
        }

        if(arr[next].en) {
          this.setTempData(txt, arr[next].en, code)
          this.selected(arr[next].en)
        }
      },
      /**
       * 设置临时变量
       * @param {String} txt
       * @param {String} code
       * @param {String} text
       */
      setTempData(txt, nextTxt, code) {
        var obj = 'temp' + nextTxt.charAt(0).toUpperCase() + nextTxt.slice(1)
        if(txt == 'province') {
          this[obj] = CityData[code]
        } else if(txt == 'city') {
          this[obj] = CityData[code];
        } else if(txt == 'district') {
          this.getApiData(txt, code)
        } else if(txt == 'street') {
          this.getApiData(txt, code)
        }
      },
      /**
       * 重置临时变量
       * @param {String} txt
       */
      resetTempData(txt) {
        var obj = 'temp' + txt.charAt(0).toUpperCase() + txt.slice(1)
        this[obj] = {}
      },
      /**
       * 获取 data
       * @param {String} txt
       */
      getData(txt) {
        let foo = 'get' + txt.charAt(0).toUpperCase() + txt.slice(1)
        return this[foo]
      },
      /**
       * 获取ApiData
       * @param {String} txt
       * @param {String} code
       */
      getApiData(txt, code) {
        var self = this
        var sn, st
        var ct = {}
        self.loading = true
        if(txt == 'district') {
          sn = 'mcStreetList'
          ct.districtId = code
          st = {
            id: 'streetId',
            name: 'streetName',
            temp: 'tempStreet'
          }
        } else {
          sn = 'communityList'
          ct.streetId = code
          st = {
            id: 'communityId',
            name: 'communityName',
            temp: 'tempCommunity'
          }
        }

        ct.pageFirst = 1
        ct.pageSize = 50

        if(this.debug) {
          console.log(txt, sn, ct);
        }
        apiSource({
          type: 'outer',
          service: sn,
          ct: ct

        }).then((res) => {
          if(this.debug) {
            console.log('res --> ', res);
          }
          console.log('Array.isArray(res', Array.isArray(res))
          if(Array.isArray(res)) {
            var rs = {}
            res.forEach(o => {
              rs[o[st.id]] = o[st.name]
            })
            self[st.temp] = rs
          } else {// 获取街道数据为空
            this.tempStreet = {}
          }
          self.loading = false
      })
      },
      /**
       * 判断是否有数据
       * @param {String} txt
       */
      isEmpty(txt) {
        let temp = 'temp' + txt.charAt(0).toUpperCase() + txt.slice(1)
        for(let prop in this[temp]) {
          return !true
        }
        return !false
      },
      /**
       * 查询tab
       * @param {String} tab
       */
      selected(tab) {
        this.tab = tab;
      },
      /**
       * 确定方法
       */
      submitHandle() {
        this.selectCb(this.site)
        this.submitCb(this.site)
        this.visible = false;
      },
      /**
       * 取消方法
       */
      cancelHandle() {
        this.visible = false;
        for(let p in this.site) {
          this.site[p].code = ''
          this.site[p].text = ''
        }
        this.cancelCb()
      },
      /**
       * 打开 添加新社区
       */
      showAddCommunity () {
        this.adding = true
      },
      /**
       * 添加新社区
       */
      addCommunityHandle() {
        apiSource({
          type: 'outer',
          service: 'communityAdd',
          ct: {
            "streetId": this.site.street.code,
            "communityName": this.addCommunityName,
            "address": ""
          }
        }).then((res) => {
          this.getApiData('community', this.site.street.code)
        });
      }
    }
  }
</script>

<style>

  .city-select-sure {
    position: absolute;
    right: 5px;
    top: 5px;
    color: #fff;
    border: none;
    padding: 3px 8px;
    border-radius: 3px;
    background-color: #46A4FF;
  }

  .city-select-sure:hover {
    background-color: #3478be;
  }

  .city-picker-dropdown {
    position: absolute;
    outline: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    z-index: 999999;
    min-width: 420px;
    margin-bottom: 20px;
    left: 15px;
    top: 35px;
    width: 360px;
  }

  .city-select-wrap {
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.5);
  }

  .city-select-tab {
    border-bottom: 1px solid #ccc;
    background: #f0f0f0;
    font-size: 13px;
    height: 35px;
  }

  .city-select-tab > span {
    display: block;
    float: left;
    padding: 7px 20px;
    border-left: 1px solid #ccc;
    border-bottom: 1px solid transparent;
    color: #4D4D4D;
    text-align: center;
    outline: 0;
    text-decoration: none;
    cursor: pointer;
    font-size: 14px;
    margin-bottom: -1px;
  }

  .city-select-tab > span.active {
    background: #fff;
    border-bottom: 1px solid #fff;
    color: #46A4FF;
  }

  .city-select-tab > span:first-child {
    border-left: none;
  }

  .city-select-tab > span:last-child.active {
    border-right: 1px solid #ccc;
  }

  .city-select-content {
    position: relative;
    width: 100%;
    min-height: 120px;
    background-color: #fff;
    padding: 10px 15px 0;
  }

  .city-add {
    margin: 0 -15px;
    border-top: 1px solid #ddd;
    padding: 10px 25px;
    font-size: 13px;
  }

  .city-select {
    font-size: 13px;
    min-height: 80px;
  }

  .city-select dl {
    line-height: 2;
    clear: both;
    padding: 3px 0;
    margin: 0;
  }

  .city-select dt {
    position: absolute;
    width: 2.5em;
    font-weight: 500;
    text-align: right;
    line-height: 2;
  }

  .city-select dd {
    margin-left: 0;
    line-height: 2;
  }

  .city-select span {
    display: inline-block;
    padding: 0 10px;
    outline: 0;
    text-decoration: none;
    white-space: nowrap;
    margin-right: 2px;
    color: #333;
    cursor: pointer;
  }

  .city-select span:hover,
  .city-select span:focus {
    background-color: #f1f8ff;
    border-radius: 2px;
    color: #46A4FF;
  }

  .city-select span.active {
    background-color: #46A4FF;
    color: #fff;
    border-radius: 2px;
  }
</style>
